package com.dslcode.cloud.provider.goods.service;

import com.dslcode.cloud.common.dto.goods.GoodsBuyDTO;
import com.dslcode.cloud.common.dto.goods.GoodsDTO;
import com.dslcode.cloud.common.model.goods.Goods;
import com.dslcode.cloud.common.utils.PropertyUtil;
import com.dslcode.cloud.provider.goods.mapper.GoodsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * Created by dongsilin on 2017/9/25.
 */
@Slf4j
@Service
public class GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;


    public GoodsDTO findDetail(Long id) {
        return goodsMapper.findDetail(id);
    }

    public Goods findById(Long id) {
        return goodsMapper.findById(id);
    }

    public GoodsBuyDTO checkStorage(Long id, int buyNum) throws Exception {
        Goods goods = findById(id);
        if (goods.getStorage().intValue() < buyNum) throw new Exception(goods.getName()+"，库存不足");
        GoodsBuyDTO goodsBuy = PropertyUtil.dozerMapper(goods, GoodsBuyDTO.class);
        goodsBuy.setBuyNum(buyNum);
        return goodsBuy;
    }

    @Transactional
    public void reduceStorage(Set<GoodsBuyDTO> goodsBuyDTOs) throws Exception {
        for (GoodsBuyDTO goodsBuy : goodsBuyDTOs){
            Integer i = goodsMapper.reduceStorage(goodsBuy);
            if (null == i || i < 1 ) throw new Exception("商品：" + goodsBuy.getName() + ", 库存不足");
        }
    }

}
